package com.iqilu.ksd.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.facebook.drawee.view.SimpleDraweeView;
import com.google.gson.reflect.TypeToken;
import com.iqilu.ksd.MyApplication;
import com.iqilu.ksd.R;
import com.iqilu.ksd.adapter.NewsAdapter;
import com.iqilu.ksd.adapter.SubsDetaileAdapter;
import com.iqilu.ksd.bean.NewsItemBean;
import com.iqilu.ksd.bean.UserBean;
import com.iqilu.ksd.constant.Api;
import com.iqilu.ksd.constant.Config;
import com.iqilu.ksd.constant.NewsType;
import com.iqilu.ksd.event.ChangeUserInfoEvent;
import com.iqilu.ksd.event.SubsChangeEvent;
import com.iqilu.ksd.utils.ArrayUtils;
import com.iqilu.ksd.utils.ConvertUtils;
import com.iqilu.ksd.utils.JSONUtils;
import com.iqilu.ksd.utils.ScreenUtils;
import com.iqilu.ksd.utils.ShareUtils;
import com.jaeger.library.StatusBarUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

import cn.sharesdk.framework.Platform;
import okhttp3.Call;
import okhttp3.RequestBody;

/**
 * Created by Coofee on 2017/4/17.
 */

public class SubsDetailActivity extends BaseActivity {

    private UserBean user;
    private int catId;
    private int page;
    private int subscribed;
    private int subscribenum;
    private String catName;
    private String thumb;
    private String shareIcon;
    private String shareUrl;
    private ArrayList<NewsItemBean> list;
    private SubsDetaileAdapter adapter;

    private View header;
    private ImageView btBack;
    private ImageView btShare;
    private SimpleDraweeView imgThumb;
    private TextView tvCatname;
    private TextView tvTitle;
    private ImageView btSubs;
    private TextView tvCount;
    private XRefreshView xRefreshView;
    private RecyclerView rvList;
    private RelativeLayout layEmpty;
    private ImageView btReload;
    private RelativeLayout layLoading;
    private RelativeLayout layHead;

    private LinearLayoutManager layoutManager;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_subsdetail);
        StatusBarUtil.setColor(this, ContextCompat.getColor(this, R.color.blue_dark), Config.STATUSBAR_ALPHA);
        user = ((MyApplication) getApplication()).getUser();
        initView();
        catId = getIntent().getIntExtra("catid", 0);
        adapter = new SubsDetaileAdapter(this);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(this));
        adapter.setOnItemClickListener(onItemClickListener);
        header = adapter.setHeaderView(R.layout.fragment_subsdetail_head, rvList);
        rvList.setAdapter(adapter);
        xRefreshView.setPullRefreshEnable(false);
        xRefreshView.setPullLoadEnable(true);
        xRefreshView.setMoveForHorizontal(true);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                page = 1;
                getList();
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                page++;
                getList();
            }
        });

        btReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                page = 1;
                layLoading.setVisibility(View.VISIBLE);
                layHead.setVisibility(View.VISIBLE);
                xRefreshView.setVisibility(View.VISIBLE);
                getList();
            }
        });

        btBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        btShare.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                toShare();
            }
        });

        rvList.addOnScrollListener(new RecyclerView.OnScrollListener() {

            private float totalDy = 0;

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                totalDy += dy;
                int mPoition = layoutManager.findFirstVisibleItemPosition();
                if (mPoition == 0) {
                    setToolBarAlpha(totalDy);
                }
            }
        });

        page = 1;
        getList();
    }

    private void initView() {
        btBack = getView(R.id.bt_back);
        btShare = getView(R.id.bt_share);
        tvTitle = getView(R.id.tv_title);
        setZHTypeface(tvTitle);
        xRefreshView = getView(R.id.xRefreshView);
        rvList = getView(R.id.rv_list);
        layEmpty = getView(R.id.lay_empty);
        btReload = getView(R.id.bt_reload);
        layLoading = getView(R.id.lay_loading);
        layHead = getView(R.id.lay_head);
        layHead.setAlpha(0);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(OrientationHelper.VERTICAL);
        rvList.setLayoutManager(layoutManager);
    }

    private void initHead(String thumb) {
        imgThumb = (SimpleDraweeView) header.findViewById(R.id.img_thumb);
        tvCatname = (TextView) header.findViewById(R.id.tv_catname);
        btSubs = (ImageView) header.findViewById(R.id.bt_subs);
        tvCount = (TextView) header.findViewById(R.id.tv_count);
        setZHTypeface(tvCatname);
        imgThumb.setImageURI(Uri.parse(thumb));
        tvCatname.setText(catName);
        tvTitle.setText(catName);
        if (subscribed == 1) {
            btSubs.setImageResource(R.drawable.bt_subscribed);
        } else {
            btSubs.setImageResource(R.drawable.bt_subscribe);
        }
        tvCount.setText(String.format(getString(R.string.subs_count), "" + subscribenum));

        btSubs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (user == null || user.getId() < 1) {
                    startActivity(new Intent(SubsDetailActivity.this, LoginActivity.class));
                    return;
                }
                if (subscribed == 1) {
                    delSubscribe();
                } else {
                    addSubscribe();
                }
            }
        });
    }

    private void setToolBarAlpha(float length) {
        float height = ConvertUtils.dp2px(this, 120);
        float mAlpha = length / height;
        if (mAlpha > 1.0f) {
            mAlpha = 1.0f;
        }
        layHead.setAlpha(mAlpha);
    }

    private void getList() {
        String url = Api.URL_SUBSCRIBE_CATE + "?page=" + page + "&catid=" + catId;
        OkHttpUtils.get().url(url).build().execute(new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                afterRequest();
                if (page == 1) {
                    setEmpty();
                }
            }

            @Override
            public void onResponse(String response, int id) {
                afterRequest();
                ArrayList<NewsItemBean> data = JSONUtils.requestList(response, "data.infos", new TypeToken<ArrayList<NewsItemBean>>() {
                });
                if (page == 1) {
                    if (data == null || data.size() == 0) {
                        setEmpty();
                        return;
                    }
                    list = data;
                    adapter.setData(list);
                    thumb = JSONUtils.filterString(response, "data.thumb");
                    catName = JSONUtils.filterString(response, "data.catname");
                    subscribed = JSONUtils.filterInt(response, "data.subscribed", 0);
                    subscribenum = JSONUtils.filterInt(response, "data.subscribenum", 0);
                    shareIcon = JSONUtils.filterString(response, "data.shareicon");
                    shareUrl = JSONUtils.filterString(response, "data.shareurl");
                    initHead(thumb);
                } else {
                    data = ArrayUtils.removeSame(list, data);
                    if (data == null || data.size() == 0) {
                        Toast.makeText(SubsDetailActivity.this, R.string.list_not_have, Toast.LENGTH_SHORT).show();
                        return;
                    }
                    if (list == null) {
                        return;
                    }
                    list.addAll(data);
                    adapter.setData(list);
                }
                adapter.notifyDataSetChanged();
            }
        });
    }

    private SubsDetaileAdapter.OnItemClickListener onItemClickListener = new SubsDetaileAdapter.OnItemClickListener() {
        @Override
        public void OnItemClickListener(View view, int position) {
            Intent intent = null;
            NewsItemBean item = list.get(position - 1);
            if (item.getType().equals(NewsType.HEAD)) {
                item.setType(item.getRealtype());
            }
            if (item.getType().equals(NewsType.ARTICLE)) {
                intent = new Intent(SubsDetailActivity.this, NewsDetailActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
            } else if (item.getType().equals(NewsType.GALLERY) || item.getType().equals(NewsType.PHOTO)) {
                intent = new Intent(SubsDetailActivity.this, GalleryActivity.class);
                intent.putExtra("id", item.getId());
                intent.putExtra("catId", item.getCatid());
                intent.putExtra("position", 0);
            } else if (item.getType().equals(NewsType.AD) || item.getType().equals(NewsType.URL)) {
                intent = new Intent(SubsDetailActivity.this, ADActivity.class);
                intent.putExtra("title", item.getTitle());
                intent.putExtra("type", item.getType());
                intent.putExtra("adUrl", item.getUrl());
                if (item.getType().equals(NewsType.AD)) {
                    intent.putExtra("shareicon", item.getShareicon());
                } else {
                    intent.putExtra("thumb", item.getThumb());
                }
            } else if (item.getType().equals(NewsType.LIVE)) {
                intent = new Intent(SubsDetailActivity.this, LiveActivity.class);
                intent.putExtra("id", item.getId());
            } else if (item.getType().equals(NewsType.CLUE)) {
                intent = new Intent(SubsDetailActivity.this, PaikeActivity.class);
                intent.putExtra("id", item.getId());
            }
            if (intent != null) {
                startActivity(intent);
            }
        }
    };

    private void toShare(){
        Platform.ShareParams sp = new Platform.ShareParams();
        sp.setTitle(catName);
        sp.setTitleUrl(shareUrl); // 标题的超链接
        sp.setText(catName);
        sp.setSiteUrl(shareUrl);
        sp.setUrl(shareUrl);
        sp.setImageUrl(shareIcon);//分享网络图片
        sp.setSite(getString(R.string.app_name));
        ShareUtils.getInstance().setShareParams(this, sp).show();
    }

    private void afterRequest() {
        layLoading.setVisibility(View.GONE);
        layEmpty.setVisibility(View.GONE);
        if (page == 1) {
            xRefreshView.stopRefresh();
        } else {
            xRefreshView.stopLoadMore();
        }
    }

    private void setEmpty() {
        adapter.setData(null);
        adapter.notifyDataSetChanged();
        layEmpty.setVisibility(View.VISIBLE);
        layHead.setVisibility(View.GONE);
        xRefreshView.setVisibility(View.GONE);
    }

    private void addSubscribe() {
        String url = Api.URL_SUBSCRIBE + "?catid=" + catId + "&catname=" + catName + "&type=article";
        OkHttpUtils
                .put()
                .url(url)
                .requestBody(RequestBody.create(null, "something"))
                .tag(this)
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(SubsDetailActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        int status = 0;
                        status = JSONUtils.filterInt(response, "status", 0);
                        if (status == 1) {
                            subscribed = 1;
                            btSubs.setImageResource(R.drawable.bt_subscribed);
                            Toast.makeText(SubsDetailActivity.this, R.string.my_add_success, Toast.LENGTH_SHORT).show();
                            EventBus.getDefault().post(new SubsChangeEvent());
                        } else {
                            Toast.makeText(SubsDetailActivity.this, R.string.my_add_error, Toast.LENGTH_SHORT).show();
                        }
                    }
                });
    }

    private void delSubscribe() {
        String url = Api.URL_SUBSCRIBE + "?catid=" + catId + "&type=article";
        OkHttpUtils.delete().url(url).tag(this).build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Toast.makeText(SubsDetailActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(String response, int id) {
                int status = 0;
                status = JSONUtils.filterInt(response, "status", 0);
                if (status == 1) {
                    subscribed = 0;
                    btSubs.setImageResource(R.drawable.bt_subscribe);
                    Toast.makeText(SubsDetailActivity.this, R.string.my_del_success, Toast.LENGTH_SHORT).show();
                    EventBus.getDefault().post(new SubsChangeEvent());
                } else {
                    Toast.makeText(SubsDetailActivity.this, R.string.my_del_error, Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.POSTING)
    public void onMessage(ChangeUserInfoEvent event) {
        user = ((MyApplication) getApplication()).getUser();
        page = 1;
        getList();
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }
}
